<?php
/**
 * $Id$
 *  @package	Joomla
 *  @author Daniel Eliasson
* 	@copyright	Copyright (C) 2010 Stilero. All rights reserved.
* 	@license	GNU/GPL, see LICENSE.php
* 	Joomla! is free software. This version may have been modified pursuant
* 	to the GNU General Public License, and as distributed it includes or
* 	is derivative of works licensed under the GNU General Public License or
* 	other free or open source software licenses.
*/

// no direct access
defined('_JEXEC') or die('Restricted access'); 
jimport( 'joomla.application.component.model' );

/**
* @package		Joomla
* @subpackage	Polls
*/
class VmcompetitionModelCompete extends JModel
{
	/**
	 * Add vote
	 * @param int The id of the poll
	 * @param int The id of the option selected
	 */
	function compete( $competition_id, $name, $email, $linkurl, $comment, $validated )
	{
		$db 				= 	$this->getDBO();
		$comp_id			= 	(int) $competition_id;
		$name				= 	(string) $name;
		$email				= 	(string) $email;
		$linkurl			= 	(string) $linkurl;
		$comment				= 	(string) $comment;
		$validated				= 	(int) $validated;

		$date =& JFactory::getDate();

		$query = "INSERT INTO #__vm_competition_contestants ("
			." `cid` ,"
			." `comp_id` ,"
			." `name` ,"
			." `linkurl` ,"
			." `email` ,"
			." `date` ,"
			." `comment`, "
			." `verified` "
			
			.") VALUES ("
			
			." NULL, "
			." '".(int) $comp_id."',"
			." '".(string) $name."',"
			." '".(string) $linkurl."',"
			." '".(string) $email."',"
			." ".$db->Quote($date->toMySQL())." ,"
			." '".(string) $comment."',"
			." '".(int) $validated."'"
			
			." );";
			
			
		$db->setQuery( $query );
		$db->query();
	}
	/**
	 * Validate the link provided, and also check for a backlink
	 * @param string $linkurl
	 */
	function validateURL($linkurl){
		$linkurl 	=	(string)$linkurl;
		
		//$urlregex = "^(https?|ftp)\:\/\/([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*(\:[0-9]{2,5})?(\/([a-z0-9+\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?\$";
		$urlregex = "/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i";
		
		//if (eregi($urlregex, $linkurl)) {
		if (preg_match($urlregex, $linkurl)) {
			return true;
		} else {
			return false;
		}
		
	}
	
	/**
	 * Check the remote link for backlink
	 * 
	 * @param string $remote_url
	 * @param string $your_link
	 */
	function checkBacklink($remote_url, $your_link) {
	    $match_pattern = preg_quote(rtrim($your_link, "/"), "/");
	    $found = false;
	    if ($handle = @fopen($remote_url, "r")) {
	        while (!feof($handle)) {
	            $part = fread($handle, 1024);
	            if (preg_match("/<a(.*)href=[\"']".$match_pattern.
	"(\/?)[\"'](.*)>(.*)<\/a>/", $part)) {
	                $found = true;
	                break;
	            }
	        }
	        fclose($handle);
	    }
	    return $found;
	}
}

?>
